<template>
  <div class="excel-preview-wrapper">
    <!-- 弹窗 -->
    <el-dialog
      :model-value="openStatus"
      title="洪涝灾害评估数据预览"
      width="80%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <div v-if="loading" class="loading-text">正在加载，请稍候...</div>

      <el-table
        v-else
        :data="tableData"
        border
        max-height="60vh"
        style="word-break: break-word;"
        v-loading="loading"
      >
        <el-table-column
          v-for="(col, index) in tableColumns"
          :key="index"
          :prop="col"
          :label="col"
          min-width="120"
          show-overflow-tooltip
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue'
import * as XLSX from 'xlsx'

const props = defineProps({
  openStatus: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['close'])

const loading = ref(false)
const tableData = ref([])
const tableColumns = ref([])

// Excel 文件地址（需支持 CORS）
const excelUrl = 'http://123.57.240.141:3008/api/excel-stream'

// 监听外部打开状态变化
watch(
  () => props.openStatus,
  (newVal) => {
    if (newVal) {
      fetchAndParseExcel(excelUrl)
    }
  }
)

// 读取 Excel 文件数据
async function fetchAndParseExcel(url) {
  loading.value = true
  try {
    const res = await fetch(url)
    if (!res.ok) throw new Error('文件加载失败: ' + res.status)

    const arrayBuffer = await res.arrayBuffer()
    const data = new Uint8Array(arrayBuffer)

    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const json = XLSX.utils.sheet_to_json(worksheet, { defval: '' })

    tableData.value = json
    tableColumns.value = json.length ? Object.keys(json[0]) : []
  } catch (error) {
    console.error(error)
    tableData.value = []
    tableColumns.value = []
    alert('加载Excel文件失败，请检查网络和文件地址')
  } finally {
    loading.value = false
  }
}

// 弹窗关闭
function handleClose(done) {
  emit('close') // 通知父组件关闭
  tableData.value = []
  tableColumns.value = []
  done()
}
</script>

<style scoped>
.excel-preview-wrapper {
  position: relative;
}

.loading-text {
  padding: 30px;
  text-align: center;
  font-size: 16px;
}
</style>
